/* 
Scenic Graphics Library
Copyright (C) 2007 Jouni Tulkki

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USApackage scenic;
*/

package scenic;

import java.awt.Font;
import java.awt.geom.AffineTransform;
import java.util.HashMap;
import java.util.Map;


class GlyphCache {
	public static class CachedFont {
		public Font font;
		public AffineTransform transform;
		
		public CachedFont(Font font, AffineTransform transform) {
			this.font = font;
			this.transform = transform;
		}		
		
		public int hashCode() {
			return font.hashCode() ^ transform.hashCode();
		}
		
		public boolean equals(Object o) {
			CachedFont f = (CachedFont)o;
			return font.equals(f.font) && transform.equals(f.transform);
		}
	}
	
	//Map<CachedFont, GlyphImage[]>
	private Map<CachedFont, GlyphImage[]> fontMap = new HashMap<CachedFont, GlyphImage[]>();
	private CacheImage cacheImage;
		
	public GlyphCache() {
		cacheImage = new CacheImage(new ScenicImage(1024, 1024, Format.AL8));
	}

	public ScenicImage getImage() {
		return cacheImage.getCacheImage();
	}
	
	public GlyphImage[] getGlyphs(CachedFont font) {
		GlyphImage[] r = (GlyphImage[])fontMap.get(font);
		
		if(r == null) {
			r = new GlyphImage[font.font.getNumGlyphs()];
			fontMap.put(font, r);
		}
		
		return r;		
	}
	
	public GlyphImage getGlyph(CachedFont font, int glyphCode) {
		GlyphImage g = getGlyphs(font)[glyphCode];
		
//		System.out.println(g != null);
		
		if(g == null || g.cache == null || g.cache.width < 0) {
			return null;
		}
		
		return g;
	}
	
	public GlyphImage renderGlyph(CachedFont font, int glyphCode) {
		GlyphImage g = TextRenderer.renderGlyph(font.font, font.transform, glyphCode);
		
		g.cache = cacheImage.addImage(g);
		g.data = null;
		getGlyphs(font)[glyphCode] = g;
		
		return g;
	}
}
